/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package cz.hamacekj.dotaznikserver;

import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.util.Iterator;
import javax.swing.DefaultListModel;
import javax.swing.SwingUtilities;

/**
 * Model seznamu počítačů. Stará se o propagování změn jména {@link Connection Connection}
 * do seznamu počítačů.
 * @author Jan Hamáček
 */
public class ConnectionListModel extends DefaultListModel<Connection> implements Iterable<Connection>{

    @Override
    public void add(int index, Connection element) {
        element.addPropertyChangeListener(new ChangeListener(index));
        super.add(index, element);
    }
    
    @Override
    public void addElement(Connection element) {
        int index = this.size();
        this.add(index, element);
    }
    
    @Override
    public Iterator<Connection> iterator() {
        return new Iterator<Connection>() {

            int pos = -1;
            
            @Override
            public boolean hasNext() {
                return pos < ConnectionListModel.this.size()-1;
            }

            @Override
            public Connection next() {
                return ConnectionListModel.this.get(++pos);
            }

            @Override
            public void remove() {
                ConnectionListModel.this.remove(pos);
            }
        };
    }
    
    class ChangeListener implements PropertyChangeListener{
        
        private int index;

        public ChangeListener(int index) {
            this.index = index;
        }
        
        @Override
        public void propertyChange(PropertyChangeEvent evt) {
            SwingUtilities.invokeLater(new Runnable() {
                @Override
                public void run() {
                    ConnectionListModel.this.fireContentsChanged(
                            ConnectionListModel.this, index, index);
                }
            });
        }
    }
    
}
